import { ComponentPublicInstance, nextTick } from 'vue';
import * as util from '@/tool/function/util';
import { user, system } from '@/store';
import systemConfig from '@/common/config';
import * as commonUtil from '@/common/utils/util';
import api from '@/api';
import uniCrazyRouter, { beforeEach, afterEach, onError, afterNotNext } from 'uni-crazy-router';
import { setDomDarkOrWhite } from '@/tool/theme/util';
// 开放给main.js
export function setupRouter(app: any) {
  // 接收vue3的实例
  app.use(uniCrazyRouter);
  let beforeFlag = false;
  beforeEach(async (to, from, next) => {
    beforeFlag = true;
    let flag = await interceptLogin(to, from, true);
    if (flag) {
      next();
    } else {
      return;
    }
  });

  afterEach((to, from) => {
    if (!beforeFlag) {
      //未经过before时处理
      interceptLogin(to, from, false);
    }
    beforeFlag = false;
    let queryParams: any = {};
    if (to.passedParams) {
      queryParams = Object.assign(queryParams, to.passedParams);
    }
    if (to.routeParams) {
      queryParams = Object.assign(queryParams, to.routeParams);
    }
    if (to.query) {
      queryParams = Object.assign(queryParams, to.query);
    }
    //每一个页面初始后都会执行
    let serviceCode = queryParams.serviceCode;
    let serviceName = queryParams.serviceName;
    let serviceId = queryParams.serviceId;
    let menuId = queryParams.menuId;
    let menuTitle = queryParams.headerTitle;
    let infoName = queryParams.infoName;
    let areaCode = queryParams.areaCode;
    if (!infoName) {
      infoName = menuTitle;
    }
    let linkPath = to.url;
  });

  // 除了在beforeEach钩子里没有使用next导致的无法跳转的情况外，其他情况导致的跳转失败都会触发onError
  onError((to, from) => {
    uni.showToast({
      title: `${to.url} 不存在`,
      icon: 'none',
    });
  });
}
/**
 * 检查认证信息
 * @param authType
 * @returns {boolean}
 */
function checkAuthorization() {
	let token = "" as any;
	if(systemConfig.refreshTokenEnabled){
		token=user.refreshToken;
    if(!token&&!system.zlbFlag){
      token=util.getCookie(systemConfig.localRefreshTokenName);
      user.setToken(util.getCookie(systemConfig.localTokenName),token)
    }
    
	}else{
		token=user.accesstoken;
    if(!token&&!system.zlbFlag){
      token=util.getCookie(systemConfig.localTokenName);
      user.setToken(token,util.getCookie(systemConfig.localRefreshTokenName))
    }
    
	}
	
	if (token) {
		return true;
	}
	return false;
}
async function interceptLogin(to: any, from: any, beforeFlag: Boolean) {
  // #ifdef H5
  setDomDarkOrWhite();
  // #endif
  let token = user.accesstoken;
  let ignoreLogin = false;
  let path = to.url;
  let pages: any = uni.$tm.pages;
  if (path) {
    if (path === '/') {
      path = systemConfig.homePath.substring(1);
    }
    let page = pages.get(path);
    if (!page) {
      uni.showToast({
        title: '跳转的页面路由不存在！',
        icon: 'none',
      });
      return false;
    }
    let meta = page?.meta;
    if (meta && meta.ignoreLogin) {
      ignoreLogin = true;
    }
  }

  let zlbFlag = system.zlbFlag;
  let queryParams: any = {};
  if (to.passedParams) {
    queryParams = Object.assign(queryParams, to.passedParams);
  }
  if (to.routeParams) {
    queryParams = Object.assign(queryParams, to.routeParams);
  }
  if (to.query) {
    queryParams = Object.assign(queryParams, to.query);
  }
  //#ifdef H5
  if (!zlbFlag) {
    let browerInfo: any = system.browerInfo;
    if (!browerInfo || !browerInfo.browserType) {
      browerInfo = commonUtil.getBrowerInfo();
      system.setBrowerInfo(browerInfo);
    }
    let type = '';
    if (browerInfo) {
      type = browerInfo.browserType;
      if (systemConfig.systemType === 'zlb' && (type === 'zlb' || type === 'zlb-alipay' || type === 'alipay' || type === 'weixin')) {
        // 浙里办 判断登录
        zlbFlag = true;
        system.setZlbFlag(true);
        system.setShowNavBar(false);
      }
    }
  }
  let accessToken = ''; //本地登录token
  if (queryParams && queryParams.accessToken) {
    accessToken = queryParams.accessToken;
  } else {
    accessToken = util.getQueryStringByName('accessToken') || '';
  }
  if (accessToken) {
    if (accessToken != token) {
      user.setToken(accessToken,null);
    }
    const sessionData = {};
    let sessionFlag = await api.common.getUserInfoEn.post(sessionData);
    if (sessionFlag) {
      return true;
    } else {
      if (systemConfig.loginErrorType === '2') {
        if (!systemConfig.loginErrorPath) {
          uni.showToast({
            title: '登录异常页面路径不能配置为空',
            icon: 'none',
          });
          return false;
        }
        let queryData = { errorMsg: 'accessToken无效或已过期' };
        if (beforeFlag) {
          afterNotNext(() => {
            replaceAll(systemConfig.loginErrorPath, queryData);
          });
        } else {
          replaceAll(systemConfig.loginErrorPath, queryData);
        }
      } else {
        let queryData = { redirect: encodeURIComponent(getUrl('/' + to.url, queryParams)) };
        if (zlbFlag) {
          if (!systemConfig.zlbLoginPath) {
            uni.showToast({
              title: '浙里办登录跳转中间页面路径不能配置为空',
              icon: 'none',
            });
            return false;
          }
          if (beforeFlag) {
            afterNotNext(() => {
              replaceAll(systemConfig.zlbLoginPath, queryData);
            });
          } else {
            replaceAll(systemConfig.zlbLoginPath, queryData);
          }
        } else {
          if (!systemConfig.loginPath) {
            uni.showToast({
              title: '登录页面路径不能配置为空',
              icon: 'none',
            });
            return false;
          }
          if (beforeFlag) {
            afterNotNext(() => {
              replaceAll(systemConfig.loginPath, queryData);
            });
          } else {
            replaceAll(systemConfig.loginPath, queryData);
          }
        }
      }
      return false;
    }
  }

  //#endif
  let loginFlag=checkAuthorization();
  if (ignoreLogin) {
    if (loginFlag) {
      if (!user.userInfo) {
        const sessionData = {};
        await api.common.getUserInfoEn.post(sessionData);
      }
    }
    return true;
  } else {
    if (loginFlag) {
      if (zlbFlag) {
        if ('/' + to.url === systemConfig.loginPath) {
          if (beforeFlag) {
            afterNotNext(() => {
              if (systemConfig.tabBarModel === 'uni') {
                uni.switchTab({ url: systemConfig.homePath });
              } else {
                replaceAll(systemConfig.homePath, {});
              }
            });
          } else {
            if (systemConfig.tabBarModel === 'uni') {
              uni.switchTab({ url: systemConfig.homePath });
            } else {
              replaceAll(systemConfig.homePath, {});
            }
          }
          return false;
        }
      } else {
        if ('/' + to.url === systemConfig.zlbLoginPath) {
          if (beforeFlag) {
            afterNotNext(() => {
              if (systemConfig.tabBarModel === 'uni') {
                uni.switchTab({ url: systemConfig.homePath });
              } else {
                replaceAll(systemConfig.homePath, {});
              }
            });
          } else {
            if (systemConfig.tabBarModel === 'uni') {
              uni.switchTab({ url: systemConfig.homePath });
            } else {
              replaceAll(systemConfig.homePath, {});
            }
          }
          return false;
        }
      }
      if (!user.userInfo) {
        const sessionData = {};
        let sessionFlag = await api.common.getUserInfoEn.post(sessionData);
        if (sessionFlag) {
          return true;
        } else {
          if (systemConfig.loginErrorType === '2') {
            if (!systemConfig.loginErrorPath) {
              uni.showToast({
                title: '登录异常页面路径不能配置为空',
                icon: 'none',
              });
              return false;
            }
            let queryData = { errorMsg: '系统accessToken无效或已过期' };
            if (beforeFlag) {
              afterNotNext(() => {
                replaceAll(systemConfig.loginErrorPath, queryData);
              });
            } else {
              replaceAll(systemConfig.loginErrorPath, queryData);
            }
          } else {
            let queryData = { redirect: encodeURIComponent(getUrl('/' + to.url, queryParams)) };
            if (zlbFlag) {
              if (!systemConfig.zlbLoginPath) {
                uni.showToast({
                  title: '浙里办登录跳转中间页面路径不能配置为空',
                  icon: 'none',
                });
                return false;
              }
              if (beforeFlag) {
                afterNotNext(() => {
                  replaceAll(systemConfig.zlbLoginPath, queryData);
                });
              } else {
                replaceAll(systemConfig.zlbLoginPath, queryData);
              }
            } else {
              if (!systemConfig.loginPath) {
                uni.showToast({
                  title: '登录页面路径不能配置为空',
                  icon: 'none',
                });
                return false;
              }
              if (beforeFlag) {
                afterNotNext(() => {
                  replaceAll(systemConfig.loginPath, queryData);
                });
              } else {
                replaceAll(systemConfig.loginPath, queryData);
              }
            }
          }
          return false;
        }
      }
      return true;
    }
    if (zlbFlag) {
      if ('/' + to.url === systemConfig.zlbLoginPath) {
        //没有token，登录页面，直接跳转
        return true;
      }
    } else {
      if ('/' + to.url === systemConfig.loginPath) {
        //没有token，登录页面，直接跳转
        return true;
      }
    }
    let queryData = { redirect: encodeURIComponent(getUrl('/' + path, queryParams)) };
    if (zlbFlag) {
      if (!systemConfig.zlbLoginPath) {
        uni.showToast({
          title: '浙里办登录跳转中间页面路径不能配置为空',
          icon: 'none',
        });
        return false;
      }
      if (beforeFlag) {
        afterNotNext(() => {
          replaceAll(systemConfig.zlbLoginPath, queryData);
        });
      } else {
        replaceAll(systemConfig.zlbLoginPath, queryData);
      }
    } else {
      if (!systemConfig.loginPath) {
        uni.showToast({
          title: '登录页面路径不能配置为空',
          icon: 'none',
        });
        return false;
      }
      if (beforeFlag) {
        afterNotNext(() => {
          replaceAll(systemConfig.loginPath, queryData);
        });
      } else {
        replaceAll(systemConfig.loginPath, queryData);
      }
    }
  }
  return false;
}
const getUrl = (url: string, query: any) => {
  let thisUrl = url;
  if (!util.isEmpty(query) && util.isObject(query)) {
    Object.keys(query).forEach((key) => {
      if (!util.isEmpty(query[key])) {
        if (util.isObject(query[key])) {
          thisUrl = util.httpUrlAddKey(thisUrl, key, JSON.stringify(query[key]));
        } else {
          thisUrl = util.httpUrlAddKey(thisUrl, key, query[key]);
        }
      }
    });
  }
  return thisUrl;
};
const push = (url: string, query: any) => {
  uni.navigateTo({ url: getUrl(url, query) });
};
const replace = (url: string, query: any) => {
  uni.redirectTo({ url: getUrl(url, query) });
};
const replaceAll = (url: string, query: any) => {
  uni.reLaunch({ url: getUrl(url, query) });
};
const back = (num: number) => {
  uni.navigateBack({
    delta: num,
  });
};
const switchTab = (url: string, query: any) => {
  uni.switchTab({ url: getUrl(url, query) });
};
export default {
  push,
  replace,
  replaceAll,
  back,
  switchTab,
};
